import axios from 'axios';
import {ElMessage} from "element-plus";
import router from "@/router";
import userStore from "@/store/UserStore"
import pinia from "@/store/pinia";

const request = axios.create({
    timeout: 5000,
})

const store = userStore(pinia)
// 设置拦截器，拦截所有的request对象的请求，修改Content-Type 为 json
request.interceptors.request.use(config => {
    // config.headers['Content-Type'] = 'application/json;charset=utf-8'
    // 为每个请求的header 添加token
    let token = store.token
    // console.log(admin)
    if (token) {
        config.headers['token'] = token
    } else {
        config.headers['token'] = ""
    }
    return config
}, error => {
    return Promise.reject(error)
})

request.interceptors.response.use(function (response) {
    return response
}, error => {
    // 4xx/5xx 的响应会到这里
    // 解构error.response，按照状态码转换
    let {data, status} = error.response
    // console.log(data.code)
    // if (data.code !== 200){
    //     console.log("错误，跳转错误页面")
    //     router.push({name: 'errorPage', params: {msg: data.msg, status: data.code}})
    // }
    if (status === 401) {
        console.log(data)
        ElMessage.error(data.error)
        router.push({name: 'login'})
    } else if (status === 403) {
        // 页面转发到错误页
        router.push({name: 'errorPage', params: {msg: "没有登录后台权限！", status: status}})
    } else if (status >= 400) {
        // 页面转发到错误页
        router.push({name: 'errorPage', params: {msg: data.error, status: status}})
    } else {
        return Promise.reject(error)
    }
})

export default request
